import React, { useState, useEffect } from 'react'
import { useParams } from 'react-router-dom'
import { message, Row, Col, Button, Image, Alert } from 'antd'
import moment from 'moment'
import { payments } from '@/constants/cart'
import { typeOrder } from '@/types/user'
import { getOrder, payOrder, receiveOrder, deliverOrder } from '@/api/order'
import { showLoading, hideLoading, $confirm } from '@/register/globalFun'
import { typeOrderProductItem } from '@/types/cart'
import './index.scss'

const Order = () => {
  const { id, auth } = useParams < { id: string, auth:string } >()
  const [order, setOrder] = useState<typeOrder>()

  useEffect(() => {
    loadOrder()
  }, [])

  const loadOrder = async() => {
    try {
      showLoading()
      const res = await getOrder(id)

      setOrder(res.data)
      console.log(res.data)
    } catch (err) {
      console.log(err)
    }
    hideLoading()
  }

  interface authBtnReturn {
    btnText:string,
    tip:string,
    successText: string,
    api: (id:string) => Promise<any>
  }
  const authBtn = () => {
    if (!order) {
      return {
        btnText: '',
        tip: '',
        successText: '',
        api: payOrder
      }
    }
    const authMap:{
      [key:string]: authBtnReturn
    } = {
      deliver: {
        btnText: '确认发货',
        tip: '确认已经发货？',
        successText: '发货成功',
        api: deliverOrder
      },
      received: {
        btnText: '确认收货',
        tip: '确认已经收货？',
        successText: '收货成功',
        api: receiveOrder
      },
      pay: {
        btnText: '支付订单',
        tip: '确认支付订单',
        successText: '支付成功',
        api: payOrder
      }
    }

    if (auth === 'admin' && !order.isDelivered) {
      return authMap.deliver
    } else if (auth === 'user' && !order.isPaid) {
      return authMap.pay
    } else if (auth === 'user' && !order.isReceived) {
      return authMap.received
    }
    return {
      btnText: '',
      tip: '',
      successText: '',
      api: payOrder
    }
  }

  return order
    ? (
      <div className="order-detail">
        <Row
          align="top"
          className="container"
          gutter={[30, 0]}
        >
          <Col
            className="user-shopping-info"
            flex={1}
          >
            <div className="item">
              <h2>收货地址</h2>
              <p>
                <span>收货人:&emsp;</span>
                <strong>{order.user.name}</strong>
              </p>
              <p>
                <span>邮箱:&emsp;</span>
                <strong>{order.user.email}</strong>
              </p>
              <p>
                <span>详细地址:&emsp;</span>
                <strong>{order.shippingAddress.province}{order.shippingAddress.city}{order.shippingAddress.address} {order.shippingAddress.postalCode}</strong>
              </p>
              {/* 收货状态 */}
              {
                order.isDelivered
                  ? (
                    <Alert
                      message={`商品已发货, 发货时间:${ moment(order.deliveredAt).format('YYYY/MM/DD HH:mm:ss') }`}
                      style={{ width: '100%' }}
                      type="success"
                    />
                  )
                  : (
                    <Alert
                      message={`商品未发货`}
                      style={{ width: '100%' }}
                      type="error"
                    />
                  )
              }
            </div>
            <div className="item">
              <h2>支付方式</h2>
              <p>
                <span>支付方式:&emsp;</span>
                <strong>{payments[ 'wx' ]}</strong>
              </p>
              {
                order.isPaid
                  ? (
                    <Alert
                      message={`已支付, 支付时间:${ moment(order.paidAt).format('YYYY/MM/DD HH:mm:ss') }`}
                      style={{ width: '100%' }}
                      type="success"
                    />
                  )
                  : (
                    <Alert
                      message={`未支付`}
                      style={{ width: '100%' }}
                      type="error"
                    />
                  )
              }
            </div>
            <div className="item">
              <h2>商品信息</h2>
              {order.productsItems.map((cart:typeOrderProductItem) => (
                <Row
                  align="middle"
                  className="item cart-item"
                  key={cart._id}
                >
                  <Col flex={0}>
                    <Image
                      src={cart.image}
                      width={60}
                    />
                  </Col>
                  <Col flex={1}>
                    {cart.name}
                  </Col>
                  <Col flex={0} >
                    {cart.qty} x {cart.price} = {cart.qty * cart.price}
                  </Col>
                </Row>
              ))}
            </div>
          </Col>
          <Col
            className="calc-result"
            span={8}
          >
            <div className="item">
              <Row>
                <Col flex={1}>商品总价: </Col>
                <Col>￥{order.totalPrice}</Col>
              </Row>
            </div>
            <div className="item">
              <Row>
                <Col flex={1}>运费: </Col>
                <Col>￥{order.shippingPrice}</Col>
              </Row>
            </div>
            <div className="item">
              <Row>
                <Col flex={1}>订单总价: </Col>
                <Col>￥{order.totalPrice + order.shippingPrice}</Col>
              </Row>
            </div>
            {
              authBtn() && (
                <Button
                  className="confirm-received-btn"
                  onClick={() => {
                    $confirm(authBtn().tip, async() => {
                      const res = await authBtn().api(order._id)

                      setOrder(res.data)
                      message.success(authBtn().successText)
                    })
                  }}
                  size="large"
                  type="primary"
                >
                  {authBtn().btnText}
                </Button>
              )
            }
          </Col>
        </Row>
      </div>
    )
    : null
}

export default Order
